<?php

namespace app\admin\controller\official;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\official\OfficialRule;

/**
 * 栏目管理
 *
 * @icon fa fa-circle-o
 */
class OfficialCategory extends Backend
{

    /**
     * OfficialCategory模型对象
     * @var \app\admin\model\official\OfficialCategory
     */
    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];
    protected $category_son = [];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\official\OfficialCategory;

        //更新配置文件
        $this->update_data();

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        $arr = [];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
            if ($v['status'] == 2 && $v['official_rule_id']) {
                $official_rule = (new OfficialRule())->where('id', $v['official_rule_id'])->find();
                $v['official_rule_name'] = !empty($official_rule) ? $official_rule['name'] : '';
            } else {
                $v['official_rule_name'] = '-';
            }
            //点击前端导航
            $v['web_url'] = (($v['is_nav_show'] == 1) || ($v['is_flooter_nav_show'] == 1))?get_cate_url($v):'';
            $arr[] = $v;
        }
        $this->categorylist = $arr;

        $official_rule = (new OfficialRule())->where('status', 1)->order('weigh', 'desc')->select();
        $this->view->assign("official_rule", $official_rule);
        $this->view->assign("categorylist", $this->categorylist);
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isNavShowList", $this->model->getIsNavShowList());
        $this->view->assign("isFlooterNavShowList", $this->model->getIsFlooterNavShowList());
        $this->view->assign("languageList", $this->model->getLanguageList());
    }

    /**
     * 根据路由规则查询子级菜单
     * @param $rule_id 规则id
     * @param $son_id 父级栏目id
     */
    public function get_select($rule_id,$son_id = 0){

        //栏目数据
        $official_category = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'official_tree_category.php';
        $official_category = include $official_category;
        //查询数据
        foreach ($official_category as $key => $item){
            if ($item['official_rule_id'] != $rule_id){
                unset($official_category[$key]);
            }else{
                foreach ($item['son'] as $k => $v){
                    if ($v['official_rule_id'] != $rule_id){
                        unset($official_category[$key]['son'][$k]);
                    }
                }
            }
        }
        return $official_category;
    }


    /**
     * 更改首页默认栏目
     */
    public function config()
    {
        //更新配置文件
        $this->update_data();
        //默认栏目数据
        $defult_index_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'defult_index.php';
        $defult_index = include $defult_index_url;
        $this->assign('defult_index',$defult_index);
        //获取产品栏目
        $product_data = $this->get_select(1,9);
        $this->assign('product_data',$product_data);
        //获取所有栏目
        $this->assign('all_category',$this->categorylist);
        //获取新闻栏目
        $journalism_data = $this->get_select(3,6);
        $this->assign('journalism_data',$journalism_data);


        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    $defult_index_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'defult_index.php';
                    file_put_contents(
                        $defult_index_url,
                        '<?php' . "\n\nreturn " . var_export_short($params) . ";\n"
                    );
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查看 用于轮播图多选
     */
    public function indextwo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $selectpage = $this->selectpage();
                return $selectpage;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 递归查询id数组
     * @param $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function select_son_ids($id)
    {
        $this->category_son[] = $id;
        $son_list = $this->model->where('pid', $id)->field(['id,pid'])->select();
        if (count($son_list)) {
            foreach ($son_list as $item) {
                $this->select_son_ids($item['id']);
            }
        }
    }

    /**
     * 更新配置文件
     */
    public function update_data(){
        //更新配置文件
        $official_tree_category_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'official_tree_category.php';
        $official_category = (new \addons\official\model\OfficialCategory())
            ->with(['son'])
            ->where('pid', 0)
            ->field(['content', 'e_content'], true)
            ->where('deletetime', null)
            ->order('weigh', 'desc')
            ->select();
        $tree_category_all = [];
        foreach ($official_category as $item) {
            $tree_category_all[] = $item->toArray();
        }
        file_put_contents(
            $official_tree_category_url,
            '<?php' . "\n\nreturn " . var_export_short($tree_category_all) . ";\n"
        );
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $old_category = $this->model->where('id', $ids)->find();
                    //-----栏目筛选
                    if ($params['pid'] > 0) {
                        $this->category_son = [];
                        if ($params['pid']) {
                            $this->select_son_ids($ids);
                        }
                        if (in_array($params['pid'], $this->category_son)) {
                            throw new Exception('您的父级不能选择自己及以下栏目');
                        }
                    }

                    $result = $row->allowField(true)->save($params);

                    //更新配置文件
                    $this->update_data();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }






    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    //更新配置文件
                    $this->update_data();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                //更新配置文件
                $this->update_data();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }





    /**
     * 还原
     */
    public function restore($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $index => $item) {
                $count += $item->restore();
            }
            //更新配置文件
            $this->update_data();
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }




    /**
     * 查询栏目的菜单规则
     * @param $ids 栏目id
     */
    public function getRule($ids)
    {
        //获取栏目
        $cate = $this->model->get($ids);
        if ($cate['status'] != 2) {
            $this->error('请选择列表类型');
        }
        //获取规则数据
        $official_rule = (new OfficialRule())->where('id', $cate['official_rule_id'])->find();
        if (!$official_rule || !$official_rule['table_name']) {
            $this->error('栏目所属规则错误');
        }
        //返回结果
        $this->success('成功查询', '', 'official/' . $official_rule['table_name'] . '/index?ids=' . $cate['id']);
    }

}
